package com.cat.twoPointerTechnique;

import java.util.*;

/**
*   @description https://leetcode.cn/problems/find-k-closest-elements/
*   @author 曲大人的喵
*   @create 2025/8/2 10:11
*   @since JDK17
*/

public class Solution02 {

    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        List<Integer> ans = new ArrayList<>();
        int n = arr.length;
        int[][] h = new int[n][2];
        for (int i = 0; i < n; i++) {   // 算出每个数字的距离
            h[i][0] = Math.abs(arr[i] - x);
            h[i][1] = i;
        }
        Arrays.sort(h, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[0] != o2[0]) return o1[0] - o2[0];
                else return o1[1] - o2[1];
            }
        });
        for (int i = 0; i < k; i++) {
            ans.add(h[i][1]);
        }
        Collections.sort(ans);
        return ans;
    }
}
